//
//  FaceIDUtils.swift
//  telephoneBook
//
//  Created by cyptt on 2023/6/24.
//

import UIKit

import LocalAuthentication
public class CHLocalAuthUtils: NSObject {

//    static let shared = FaceIDUtils()
//    private override init() {}
    let context:LAContext = LAContext()
    
    /*
     检查人脸授权是否可用
     */
    public func isSupport()->Bool{
        return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
    }
    
    
  
    
    /*
     获取人脸授权
     */
    public func faceAuth(reason:String = "Log in to your account",successClosure:@escaping()->Void,failClosure:@escaping(_ failMsg:String)->Void){
        var error: NSError?
        if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
            
            context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason ) { success, error in
                
                let error:NSError? = error as? NSError
                if success {
                    
            
                    DispatchQueue.main.async {
                        successClosure()
                    }
                    
                } else {
                    
                    
                    var errMsg:String = ""
                    if #available(iOS 11.0, *) {
                        switch (error?.code) {
                        case LAError.systemCancel.rawValue:
                            errMsg = "系统取消授权，如其他APP切入"
                            
                            
                            break;
                            
                        case LAError.userCancel.rawValue:
                            errMsg = "用户取消验证Face ID"
                            
                            break;
                            
                        case LAError.authenticationFailed.rawValue:
                            errMsg = "授权失败"
                            
                            break;
                            
                        case LAError.passcodeNotSet.rawValue:
                            errMsg = "系统未设置密码"
                            
                            break;
                            
                        case LAError.biometryNotAvailable.rawValue:
                            
                            errMsg = "设备Face ID不可用" //例如未打开
                            break;
                            
                        case LAError.biometryNotEnrolled.rawValue:
                            errMsg = "设备Face ID不可用，用户未录入"
                            
                            break;
                            
                        case LAError.userFallback.rawValue:
                            errMsg = "授权失败，进行密码验证"
                            
                            break;
                            
                        default:
                            errMsg = "其他错误"
                            break;
                            
                        }
                    } else {
                        errMsg = "系统太低，只支持ios11上版本"
                        // Fallback on earlier versions
                    }
                    print(errMsg + ":" + (error?.localizedDescription ?? "Failed to authenticate"));
                    
                    if error?.code == LAError.userFallback.rawValue{
                        self.pwdAuth(reason: reason,successClosure: successClosure, failClosure: failClosure)
                    }else{
                        DispatchQueue.main.async {
                            failClosure(errMsg)
                        }
                    }
                   
                    
                }
            }
            
            
            
        }else{
            
            var errMsg:String = ""
            if #available(iOS 11.0, *) {
                switch (error?.code) {
                case LAError.biometryNotEnrolled.rawValue:
                    errMsg = "Face ID未注册"
                    
                    break;
                case LAError.passcodeNotSet.rawValue:
                    errMsg = "未设置密码"
                    
                    break;
                case LAError.touchIDLockout.rawValue:
                    errMsg = "Face ID被锁"
                    
                 
                    break
                    
                default:
                    errMsg = "Face ID不可用"
                    
                    break;
                    
                }
            } else {
                errMsg = "系统太低，只支持ios11上版本"
                // Fallback on earlier versions
            }
            
        
            print(errMsg + ":" + (error?.localizedDescription ?? "Can't evaluate policy"));
           
            if error?.code == LAError.touchIDLockout.rawValue{
                self.pwdAuth(reason: reason,successClosure: successClosure, failClosure: failClosure)
            }else{
                DispatchQueue.main.async {
                    failClosure(errMsg)
                }
            }
          

        }
        
    }
    
    
    public func pwdAuth(reason:String = "Log in to your account",successClosure:@escaping()->Void,failClosure:@escaping(_ failMsg:String)->Void){
        var error:NSError?
        if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error){
            context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) { success, error in
                let error:NSError? = error as? NSError
                if success {
                    
            
                    DispatchQueue.main.async {
                        successClosure()
                    }
                    
                }else{
                    
                    var errMsg:String = ""
                    switch (error?.code) {
                    case LAError.systemCancel.rawValue:
                        errMsg = "系统取消授权，如其他APP切入"
                        
                        
                        break;
                        
                    case LAError.userCancel.rawValue:
                        errMsg = "用户取消验证"
                        
                        break;
                        
                    case LAError.authenticationFailed.rawValue:
                        errMsg = "授权失败"
                        
                        break;
                        
                    case LAError.passcodeNotSet.rawValue:
                        errMsg = "系统未设置密码"
                        
                        break;
                        
                        
                    case LAError.userFallback.rawValue:
                        errMsg = "点击了回退按钮"
                        
                        break;
                        
                    default:
                        errMsg = "其他错误"
                        break;
                        
                    }
                    print(errMsg + ":" + (error?.localizedDescription ?? "Failed to authenticate"));
                    
                    
                    DispatchQueue.main.async {
                        failClosure(errMsg)
                    }
                }
            }
        }else{
            var errMsg:String = ""
            switch (error?.code) {
          
            case LAError.passcodeNotSet.rawValue:
                errMsg = "未设置密码"
                
                break;
          
                
            default:
                errMsg = "密码不可用"
                
                break;
                
            }
        
            print(errMsg + ":" + (error?.localizedDescription ?? "Can't evaluate policy"));
           
            DispatchQueue.main.async {
                failClosure(errMsg)
            }
        }
    }
}
